//
//  NetWorkTools.swift
//  weibo
//
//  Created by 张宏芝 on 15/9/1.
//  Copyright © 2015年 kama. All rights reserved.
//

import UIKit
import AFNetworking
import ReactiveCocoa

enum RequestMethod:String{
    case GET = "GET"
    case POST = "POST"
}

// 网络工具类
class NetWorkTools: AFHTTPSessionManager {
//        app的信息
        private let clientId = "3876937465"
        private let appSecret = "1351b91b869001586473906ded1318a0"
        let redirectUri = "http://www.baidu.com"
    
//    单例
    static let sharedTools:NetWorkTools = {
        var instance = NetWorkTools(baseURL: nil)
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return instance
    }()
    
//  发送微博
    func sendStatus(status:String)->RACSignal{
        let params = ["status":status]
        return request(.POST, URLString: "https://api.weibo.com/2/statuses/update.json", parameters: params)
    }
    
//    MARK:微博数据
/// - parameter since_id:   若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0
/// - parameter max_id:     若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
    
// 外部参数:第一个since_id是外部参数,在外部调用的时候,第一个参数可以省略,直接传第二个,这样写,可以在外部调用的时候不删除代码直接敲出智能提示
    func loadStatus(since_id since_id:Int,max_id:Int)->RACSignal{
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        var param = [String:AnyObject]()
        if since_id > 0 {
            param["since_id"] = since_id
        }else if max_id > 0 {
                param["max_id"] = max_id - 1
        }
        return request(.GET, URLString: urlString, parameters:param)
    }
    
///    OAuth 授权URL
///   - see:[http://open.weibo.com/wiki/Oauth2/authorize](http://open.weibo.com/wiki/Oauth2/authorize)
    var oauthUrl:NSURL{
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)"
        return NSURL(string: urlString)!
    }
    
//    获取AccessToke
/// - parameter code: 请求码/授权码
///    -see:[http://open.weibo.com/wiki/OAuth2/access_token](http://open.weibo.com/wiki/OAuth2/access_token)
    func loadAccesssToken(code:String)->RACSignal{
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id": clientId,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri":redirectUri]
//       访问网络获取的方法
        return request(.POST, URLString: urlString, parameters: params,withToken:false)
    }
    
    /// 加载用户信息
    ///
    /// - parameter uid: uid
    ///
    /// - returns: RAC Singal
    /// - see: [http://open.weibo.com/wiki/2/users/show](http://open.weibo.com/wiki/2/users/show)
    func loadUserInfo(uid:String) ->RACSignal{
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        let params = ["uid":uid]
        
        return request(.GET, URLString: urlString, parameters: params)
    }
    
///   访问网络的方法
/// - parameter method:     RequestMethod
/// - parameter URLString:  URLString
/// - parameter parameters: 数组字典
  private  func request(method:RequestMethod,URLString:String,var parameters:[String:AnyObject]?,withToken:Bool = true)->RACSignal {
        
        return RACSignal.createSignal({ (subscriber) -> RACDisposable! in
            
 /// 0.判断是否需要 token
            if withToken{
                guard let token = UserAccountViewModel.sharedUserAccount.accessToken else{
                    // token == nil
                    // 发送一个 token 为空的错误
                    subscriber.sendError(NSError(domain: "com.itheima.error", code: -1001, userInfo: ["errorMessage": "Token 为空"]))
                    return nil
                }
                // 判断是否传递了参数字典
                if parameters == nil {
                    parameters = [String: AnyObject]()
                }
                // 后续的 token 都是有值的
                parameters!["access_token"] = token
            }
            
//            1.成功回调闭包
            let successCallBack = { (task:NSURLSessionDataTask,result:AnyObject)->Void in
                subscriber.sendNext(result)
                subscriber.sendCompleted()
            }
//            2.回调失败
            let failureCallBack = { (task:NSURLSessionDataTask,error:NSError)->Void in
                print(error)
                subscriber.sendError(error)
            }
//            AFN框架的方法
            if method == .GET{
                self.GET(URLString, parameters: parameters, success: successCallBack, failure: failureCallBack)
            }else{
                self.POST(URLString, parameters: parameters, success: successCallBack, failure: failureCallBack)
            }
             return nil
        })
    }
}
